<template>
  <el-card>
    <el-button type="primary" @click="addBrand">添加品牌</el-button>
    <el-dropdown>
      <span class="el-dropdown-link">
        Dropdown List
        <el-icon class="el-icon--right">
          <arrow-down />
        </el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item>Action 1</el-dropdown-item>
          <el-dropdown-item>Action 2</el-dropdown-item>
          <el-dropdown-item>Action 3</el-dropdown-item>
          <el-dropdown-item disabled>Action 4</el-dropdown-item>
          <el-dropdown-item divided>Action 5</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <el-input v-model="input"></el-input>
    <el-table :data="dataList" style="width: 100%">
      <el-table-column prop="id" label="唯一标识" min-width="80" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="品牌logo">
        <template #default="{ row }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            size="small"
            @click="deleteHandleClick(row.id)"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="editHandleClick(row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 15px">
      <el-pagination
        v-model:current-page="data.page"
        v-model:page-size="data.limit"
        :page-sizes="[5, 10, 20, 30]"
        size="default"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
  <el-dialog title="添加品牌" v-model="dialogVisible" width="50%">
    <el-form
      :model="dataForm"
      label-width="120px"
      :rules="rules"
      ref="dataFormRef"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input v-model="dataForm.tmName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="品牌logo" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :action="'http://sph-api.atguigu.cn/admin/product/fileUpload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="dataForm.logoUrl" :src="dataForm.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import {
  getTrademarkList,
  addTrademark,
  deleteTrademark,
  undateTrademark,
} from '@/api/product/trademark'
import type {
  Itrademark,
  ItrademarkAddResponse,
} from '@/api/product/trademark/type'
import { ElMessage, ElMessageBox } from 'element-plus'

interface IData {
  id: string
  page: number
  limit: number
}
let data = ref<IData>({
  id: '',
  page: 1,
  limit: 5,
})
interface IDataForm {
  id: string
  logoUrl: string
  tmName: string
}

let dataForm = ref<IDataForm>({
  id: '',
  logoUrl: '',
  tmName: '',
})
let input = ref<string>('')
let total = ref<number>(0)
let dataList = ref<Itrademark[]>([])
let dialogVisible = ref<boolean>(false)
const dataFormRef = ref()

// 获取table表格数据
const getDataList = async () => {
  const result = await getTrademarkList(data.value)
  dataList.value = result.data.records
  total.value = result.data.total
}

const handleAvatarSuccess = (response: any, uploadFile: any) => {
  console.log(response, uploadFile)
  dataForm.value.logoUrl = response.data
}
const beforeAvatarUpload = (rawFile: any) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
  }
  return true
}

const handleSizeChange = (val: number) => {
  data.value.limit = val
  getDataList()
}

const handleCurrentChange = (val: number) => {
  data.value.page = val
  getDataList()
}

onMounted(async () => {
  getDataList()
})

const addBrand = () => {
  dialogVisible.value = true
}

const submitForm = async () => {
  await dataFormRef.value.validate()
  let res: ItrademarkAddResponse
  if (dataForm.value.id) {
    res = await undateTrademark(dataForm.value)
  } else {
    res = await addTrademark(dataForm.value)
  }
  if (res.code !== 200) {
    return ElMessage.error(`${dataForm.value.id ? '更新' : '添加'}失败`)
  }
  ElMessage.success(`${dataForm.value.id ? '更新' : '添加'}成功`)
  dialogVisible.value = false
  getDataList()
}

const deleteHandleClick = (id: number | string) => {
  ElMessageBox.confirm('确定删除当前单据?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await deleteTrademark(id)
      if (res.code !== 200) return ElMessage.error('删除失败')
      ElMessage.success('删除成功')
      getDataList()
    })
    .catch(() => {})
  // deleteTrademark
}
const editHandleClick = (row: IDataForm) => {
  dialogVisible.value = true
  dataForm.value = row
}

const rules = computed(() => {
  return {
    tmName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
    logoUrl: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  }
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
